// console.warn("popup.js init...");
require(["app", "popup/popup-jpress",
    "popup/popup-jianshu",
    "popup/popup-toutiao",
    "popup/popup-csdn",
    "popup/popup-footer"
], function(app, jpress, jianshu, toutiao, csdn) {

    // popup init
    appendApp("view/index_popup.html", "app")
        .then(function(){
            // jpress 菜单初始化
            var config = jpress.getConfig();
            var cell_jpress = $("#menu__jpress");
            cell_jpress.find("img").attr("src", config.avatar);
            cell_jpress.find(".weui-cell__ft").html(config.domain);
            cell_jpress.find(".weui-cell__bd").html(config.nickname);
            cell_jpress.unbind("click").bind("click", config.jpuid ? jpress.showMenu : jpress.initConfig);
            if(config.jpuid){
                $(".platforms-loading").show();
                initPlatforms();
            }
        });

    /**
     * 初始化各平台配置行
     */
    var initPlatforms = function(){
        jpress.getPlatforms()
            .done(function(resp){
                var enableList = [];
                var notEnableList = [];
                for(var p of resp.platforms){
                    if(p.enable){
                        enableList[enableList.length] = p;
                    } else {
                        notEnableList[notEnableList.length] = p;
                    }
                }
                // 加载条目
                for (var p of enableList){
                    appendApp("view/item-" + p.platformName + ".html", "#platformItems", false);
                    $(".platform_group").show()
                }
                // 加载条目
                for (var p of notEnableList){
                    appendApp("view/item-" + p.platformName + ".html", "#disablePlatformItems", false);
                    $(".platform_group_disable").show()
                }
            })
            .done(function(resp){
                for(var p in resp.platforms){
                    var plat = resp.platforms[p];
                    var $item = $("#menu__" + plat.platformName);
                    $item.show();
                    $item.find(".platform_name").html(plat.enable ? (plat.nickname || "异常") : "").attr("title", plat.reason);
                    $item.find(".weui-icon").hide();
                    plat.enable && $item.find(plat.valid ? ".weui-icon-success" : ".weui-icon-warn").show();
                    // 初始化
                    try{
                        // 需要在引入require模块后，暴露模块参数并与平台同名
                        eval(plat.platformName + ".init($item, " + JSON.stringify(plat) + ")")
                    } catch(e){
                        console.error(plat.platformDisplayName + "平台初始化失败", e);
                    }
                }
                $(".weui-loadmore").hide();
                $(".platforms-bottomline").show();
            })
            .fail(function(e){
                $.toptip(JSON.stringify(e), 1000, "error")
            })
    }
});
